class LocalStorageService {
    /**
     * 将对象序列化为字符串并存储到 localStorage 中
     * @param {string} key 存储的键
     * @param {*} value 存储的值（可以是任意类型）
     */
    setItem(key, value) {
        try {
            let serializedValue;
            if ((typeof value === 'object' || Array.isArray(value)) && value !== null) {
                // 对象（非数组、非函数）进行序列化
                serializedValue = JSON.stringify(value);
            } else {
                // 其他类型直接存储
                serializedValue = value;
            }
            localStorage.setItem(key, serializedValue);
        } catch (error) {
            console.error('存储数据到 localStorage 失败:', error);
        }
    }

    /**
     * 从 localStorage 中获取字符串并反序列化为对象
     * @param {string} key 存储的键
     * @returns {*} 存储的值（可以是任意类型）
     */
    getItem(key) {
        try {
            const serializedValue = localStorage.getItem(key);
            if (serializedValue === null) {
                return null;
            }
            try {
                // 尝试反序列化
                return JSON.parse(serializedValue);
            } catch (parseError) {
                // 如果反序列化失败，说明存储的是非对象类型
                return serializedValue;
            }
        } catch (error) {
            console.error('从 localStorage 获取数据失败:', error);
            return null;
        }
    }

    /**
     * 从 localStorage 中移除指定的键
     * @param {string} key 存储的键
     */
    removeItem(key) {
        localStorage.removeItem(key);
    }

    /**
     * 清空 localStorage
     */
    clear() {
        localStorage.clear();
    }
}

import CryptoJS from 'crypto-js';
import nacl from 'tweetnacl';

// 将 ArrayBuffer 转换为十六进制字符串
function arrayBufferToHex(buffer) {
    const bytes = new Uint8Array(buffer);
    return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
}

// 将 Uint8Array 转换为十六进制字符串
function uint8ArrayToHex(uint8Array) {
    return Array.from(uint8Array, byte => byte.toString(16).padStart(2, '0')).join('');
}

// 检查浏览器是否支持指定的算法
async function isAlgorithmSupported(algorithm) {
    try {
        await crypto.subtle.importKey('raw', new Uint8Array(), algorithm, false, []);
        return true;
    } catch (e) {
        return false;
    }
}

// 加密(加密文本，加密方式)
export async function calculate(message, method) {
    let hash;

    if (method === 'SHA-256' || method === null) {
        if (await isAlgorithmSupported({ name: 'SHA-256' })) {
            const encoder = new TextEncoder();
            const data = encoder.encode(message);
            hash = await crypto.subtle.digest('SHA-256', data);
        } else {
            hash = CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex);
        }
    } else if (method === 'SHA-384') {
        if (await isAlgorithmSupported({ name: 'SHA-384' })) {
            const encoder = new TextEncoder();
            const data = encoder.encode(message);
            hash = await crypto.subtle.digest('SHA-384', data);
        } else {
            hash = CryptoJS.SHA384(message).toString(CryptoJS.enc.Hex);
        }
    } else if (method === 'Ed25519') {
        if (await isAlgorithmSupported({ name: 'Ed25519' })) {
            const keyPair = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
            const encoder = new TextEncoder();
            const data = encoder.encode(message);
            const signature = await crypto.subtle.sign({ name: 'Ed25519' }, keyPair.privateKey, data);
            hash = arrayBufferToHex(signature);
        } else {
            const keyPair = nacl.sign.keyPair();
            const encoder = new TextEncoder();
            const data = encoder.encode(message);
            const signature = nacl.sign.detached(data, keyPair.secretKey);
            hash = uint8ArrayToHex(signature);
        }
    } else {
        throw new Error('Unsupported method');
    }

    return hash;
}

const localStorageService = new LocalStorageService();
export { localStorageService }